# coding=utf-8
from rest_framework import serializers

from dictionary.models import DictionaryType, DictionaryItem


class CreateDictionaryTypeSerializers(serializers.HyperlinkedModelSerializer):
    class Meta:
        fields = ('code', 'id', 'status', 'name')
        model = DictionaryType
    
    def create(self, validated_data):
        dictionary_type = super(CreateDictionaryTypeSerializers, self).create(validated_data)
        
        return dictionary_type


class EditDictionaryTypeSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        fields = ('code', 'id', 'status', 'name')
        model = DictionaryType
    
    def update(self, instance, validated_data):  # 修改数据的操作
        # instance接收的是数据库查询的单个对象, validated_data为前端传输的数据
        instance.status = validated_data.get('status', instance.status)
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        # 取出值每个字段进行保存
        return instance


class DictionaryTypeSerializers(serializers.HyperlinkedModelSerializer):
    class Meta:
        fields = ('code', 'id', 'status', 'name')
        model = DictionaryType


class DictionaryItemSerializers(serializers.HyperlinkedModelSerializer):
    class Meta:
        fields = ('sort', 'id', 'name', 'value', 'type_id')
        model = DictionaryItem


class CreateDictionaryItemSerializers(serializers.HyperlinkedModelSerializer):
    class Meta:
        fields = ('code', 'id', 'value', 'name', 'sort', 'type_id')
        model = DictionaryType
    
    def create(self, validated_data):
        dictionary_type = super(CreateDictionaryItemSerializers, self).create(validated_data)
        
        return dictionary_type


class EditDictionaryItemSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        fields = ('code', 'id', 'status', 'name')
        model = DictionaryType
    
    def update(self, instance, validated_data):  # 修改数据的操作
        # instance接收的是数据库查询的单个对象, validated_data为前端传输的数据
        instance.status = validated_data.get('status', instance.status)
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        # 取出值每个字段进行保存
        return instance
